<template>
  <div class="container-content">
    <el-form
      ref="formRef"
      :model="formObject"
      label-width="100px"
      :rules="rules"
      status-icon
      label-position="left"
    >
      <el-dropdown
        style="position: absolute; right: 50px; top: 20px; z-index: 10"
        trigger="click"
        @command="handleCommand"
      >
        <el-button size="small" type="primary">
          选单<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="salesContract">销售合同</el-dropdown-item>
          <el-dropdown-item command="saleOrder">销售订单</el-dropdown-item>
          <el-dropdown-item command="2">销售报价单</el-dropdown-item>
          <el-dropdown-item command="3">物料清单</el-dropdown-item>
          <el-dropdown-item command="4">采购订单</el-dropdown-item>
          <el-dropdown-item command="5">网上订单</el-dropdown-item>
          <el-dropdown-item command="6">预测单</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-collapse v-model="activeName" @change="handleClick">
        <el-collapse-item title="基本" name="basic">
          <el-row :gutter="15">
            <el-col v-if="rowId" :span="8">
              <el-form-item label="单据类型" prop="kingDocTypeId">
                <el-input
                  :disabled="true"
                  style="width: 100%"
                  v-model="formObject.kingDocTypeId"
                  :props="props"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col v-if="!rowId" :span="8">
              <el-form-item label="单据类型" prop="kingDocTypeId">
                <el-select
                  v-model="formObject.kingDocTypeId"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in documentTypeList"
                    :key="item.keyCode"
                    :label="item.title"
                    :value="item.keyCode"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单据编码" prop="kingDocCode">
                <el-input
                  v-model="formObject.kingDocCode"
                  placeholder="保存时自动生成"
                  clearable
                  :style="{ width: '100%' }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="日期" prop="saleDate">
                <el-date-picker
                  v-model="formObject.saleDate"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  :style="{ width: '100%' }"
                  placeholder="请输入日期"
                  clearable
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户" prop="customerName">
                <el-input
                  v-model="formObject.customerName"
                  placeholder="请输入客户"
                  clearable
                  :style="{ width: '100%' }"
                >
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-notebook-2"
                    style="cursor: pointer"
                    @click="addDialog('customer')"
                  ></i>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户地点" prop="customerAddress">
                <el-input
                  v-model="formObject.customerAddress"
                  placeholder="请输入客户地点"
                  clearable
                  :style="{ width: '100%' }"
                >
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="销售部门" prop="saleDeptName">
                <el-input
                  v-model="formObject.saleDeptName"
                  placeholder="请输入销售部门"
                  clearable
                  :style="{ width: '100%' }"
                >
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-notebook-2"
                    style="cursor: pointer"
                    @click="addDialog('saleDept')"
                  ></i>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售组" prop="saleGroupName">
                <el-input
                  v-model="formObject.saleGroupName"
                  placeholder="请输入销售组"
                  clearable
                  :style="{ width: '100%' }"
                >
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-notebook-2"
                    style="cursor: pointer"
                    @click="addDialog('saleGroup')"
                  ></i>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售员" prop="saleName">
                <el-input
                  v-model="formObject.saleName"
                  placeholder="请输入销售员"
                  clearable
                  :style="{ width: '100%' }"
                >
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-notebook-2"
                    style="cursor: pointer"
                    @click="addDialog('saleId')"
                  ></i>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="生效日" prop="effectiveDate">
                <el-date-picker
                  v-model="formObject.effectiveDate"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  :style="{ width: '100%' }"
                  placeholder="请输入日期"
                  clearable
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="失效日" prop="expirationDate">
                <el-date-picker
                  v-model="formObject.expirationDate"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  :style="{ width: '100%' }"
                  placeholder="请输入日期"
                  clearable
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="币别">
                <el-input v-model="formObject.currencyName">
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-notebook-2"
                    style="cursor: pointer"
                    @click="addDialog('currency')"
                  ></i>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="汇率">
                <el-input v-model="formObject.rate" clearable disabled>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否价外税" prop="priceTax">
                <el-radio v-model="formObject.priceTax" label="0" border
                  >否</el-radio
                >
                <el-radio v-model="formObject.priceTax" label="1" border
                  >是</el-radio
                >
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否含税" prop="isTax">
                <el-radio v-model="formObject.isTax" label="0" border
                  >否</el-radio
                >
                <el-radio v-model="formObject.isTax" label="1" border
                  >是</el-radio
                >
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="formObject.remark"
                  placeholder="请输入备注"
                  clearable
                  type="textarea"
                  :style="{ width: '100%' }"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
        <el-collapse-item title="明细" name="detail">
          <el-button
            type="text"
            size="medium"
            @click="addNewRow('materialDetailEntities')"
            >新增行</el-button
          >
          <el-table
            :data="formObject.materialDetailEntities"
            style="width: 100%"
            highlight-current-row
            border
            :summary-method="getSummaries"
            show-summary
          >
            <el-table-column label="操作" width="60">
              <template slot-scope="scope">
                <el-button
                  plain
                  icon="el-icon-minus"
                  size="mini"
                  @click="
                    handleDataDelete(
                      scope.$index,
                      scope.row,
                      'materialDetailEntities'
                    )
                  "
                ></el-button>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="55"
              align="center"
            ></el-table-column>
            <el-table-column width="200" label="物料编码" prop="materialCode">
              <template slot-scope="scope">
                <el-form-item label-width="0px" style="margin: 0">
                  <el-input
                    @focus="addDialog('material', scope.$index)"
                    v-model="scope.row.materialCode"
                  >
                    <i
                      slot="suffix"
                      @click="addDialog('material', scope.$index)"
                      class="el-input__icon el-icon-notebook-2"
                      style="cursor: pointer"
                    ></i>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="" prop="materialName">
              <template slot="header">
                物料名称<span class="required">*</span>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  label-width="0px"
                  style="margin: 0"
                  :rules="rules.materialName"
                  :prop="
                    'materialDetailEntities.' + scope.$index + '.materialName'
                  "
                >
                  <el-input v-model="scope.row.materialName"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="规格型号" prop="model">
              <template slot-scope="scope">
                <el-form-item prop="model" label-width="0px" style="margin: 0">
                  <el-input v-model="scope.row.model" disabled></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="" prop="purchaseUnitName">
              <template slot="header">
                销售单位<span class="required">*</span>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  label-width="0px"
                  style="margin: 0"
                  :rules="rules.purchaseUnitName"
                  :prop="
                    'materialDetailEntities.' +
                    scope.$index +
                    '.purchaseUnitName'
                  "
                >
                  <el-input v-model="scope.row.purchaseUnitName">
                    <i
                      slot="suffix"
                      @click="addDialog('unit', scope.$index)"
                      class="el-input__icon el-icon-notebook-2"
                      style="cursor: pointer"
                    ></i
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="销售数量" prop="number">
              <template slot-scope="scope">
                <el-form-item prop="number" label-width="0px" style="margin: 0">
                  <el-input
                    v-model="scope.row.number"
                    @change="caculateNum(scope.row, scope.$index)"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="计价单位" prop="pricingUnitName">
              <template slot-scope="scope">
                <el-form-item
                  prop="pricingUnitName"
                  label-width="0px"
                  style="margin: 0"
                >
                  <el-input v-model="scope.row.pricingUnitName">
                    <i
                      slot="suffix"
                      @click="addDialog('priceUnit', scope.$index)"
                      class="el-input__icon el-icon-notebook-2"
                      style="cursor: pointer"
                    ></i>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="计价数量" prop="pricingNum">
              <template slot-scope="scope">
                <el-form-item
                  prop="pricingNum"
                  label-width="0px"
                  style="margin: 0"
                >
                  <el-input v-model="scope.row.pricingNum"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="计价数量" prop="pricingNum">
              <template slot-scope="scope">
                <el-form-item
                  prop="pricingNum"
                  label-width="0px"
                  style="margin: 0"
                >
                  <el-input v-model="scope.row.pricingNum"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="单价" prop="price">
              <template slot-scope="scope">
                <el-form-item prop="price" label-width="0px" style="margin: 0">
                  <el-input
                    v-model="scope.row.price"
                    :disabled="formObject.isTax === '0'"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="含税单价" prop="taxPrice">
              <template slot-scope="scope">
                <el-form-item
                  prop="taxPrice"
                  label-width="0px"
                  style="margin: 0"
                >
                  <el-input v-model="scope.row.taxPrice"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="是否赠品" prop="isGiveaway" align="center">
              <template slot-scope="scope">
                <el-form-item
                  prop="isGiveaway"
                  label-width="0px"
                  style="margin: 0"
                >
                  <el-checkbox
                    :v-model="scope.row.isGiveaway"
                    clearable
                  ></el-checkbox>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="税率%" prop="taxRate" width="110">
              <template slot-scope="scope">
                <el-form-item
                  prop="taxRate"
                  label-width="0px"
                  style="margin: 0"
                >
                  <el-input
                    @change="caculateNum(scope.row, scope.$index)"
                    v-model="scope.row.taxRate"
                  >
                    <i
                      slot="suffix"
                      @click="addDialog('taxRate', scope.$index)"
                      class="el-input__icon el-icon-notebook-2"
                      style="cursor: pointer"
                    ></i>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="税额" prop="taxAmount">
              <template slot-scope="scope">
                <el-form-item
                  prop="taxAmount"
                  label-width="0px"
                  style="margin: 0"
                >
                  <el-input v-model="scope.row.taxAmount" disabled></el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="金额" prop="amountMoney">
              <template slot-scope="scope">
                <el-form-item
                  prop="amountMoney"
                  label-width="0px"
                  style="margin: 0"
                >
                  <el-input
                    v-model="scope.row.amountMoney"
                    :disabled="formObject.isTax === '0'"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="价税合计">
              <template slot-scope="scope">
                <el-form-item
                  prop="totalTaxPrice"
                  label-width="0px"
                  style="margin: 0"
                >
                  <el-input
                    @change="caculateNum(scope.row, scope.$index)"
                    v-model="scope.row.totalTaxPrice"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="ramarks">
              <template slot-scope="scope">
                <el-form-item
                  prop="ramarks	"
                  label-width="0px"
                  style="margin: 0"
                >
                  <el-input v-model="scope.row.ramarks"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="批号" prop="batchNum">
              <template slot-scope="scope">
                <el-form-item
                  prop="batchNum	"
                  label-width="0px"
                  style="margin: 0"
                >
                  <el-input v-model="scope.row.batchNum" disabled></el-input>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialog"
      append-to-body
      width="70%"
      destroy-on-close
      v-if="dialog"
    >
      <component
        :is="currentCom"
        :id="rowId"
        :visible.sync="dialog"
        @getSelectVal="getSelectVal"
      ></component>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelSelect">取 消</el-button>
        <el-button type="primary" @click="confirmSelect">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { listDept } from "@/api/system/dept";
import { getAreaList } from "@/api/area/area";
import { getOrderDetail, addList, getDocTypeList } from "@/api/system/purchase";
import { addQuotationList } from "@/api/system/sale";
import { getCompute } from "@/api/finance/info";

import SaleId from "@/components/dialog/saleId";
import Customer from "@/components/dialog/customer";
import SaleDept from "@/components/dialog/saleDept";
import BusinessGroup from "@/components/dialog/businessGroup";
import QueryMaterialList from "@/components/dialog/queryMaterialList";
import PriceUnit from "@/components/dialog/priceUnit";
import TaxRate from "@/components/dialog/taxRate";
import Currency from "@/components/dialog/currency";

export default {
  props: ["rowId"],
  components: {
    SaleId,
    Customer,
    SaleDept,
    BusinessGroup,
    QueryMaterialList,
    PriceUnit,
    TaxRate,
    Currency,
  },
  data() {
    return {
      activeName: ["basic", "detail"],
      dialog: false,
      counties: [],
      orgData: [], //创建组织弹窗列表
      orgSelect: [], //选中项
      selectItem: [],
      orgTotal: "", //创建组织弹窗分页
      dialogType: "",
      dialogIndex: "",
      currentCom: "", //弹窗组件
      dialogTitle: "", //弹窗标题
      props: {},
      formObject: {
        baseCurrency: "",
        businessType: "27",
        createBy: "",
        createTime: "",
        currency: "",
        currencyName: "",
        customerAddress: "",
        customerId: "",
        customerName: "",
        delFlag: "",
        deptId: "",
        discountInfoId: "",
        effectiveDate: "",
        expirationDate: "",
        id: "",
        instanceId: "",
        isTax: "",
        kingDocCode: "",
        kingDocTypeId: "",
        modelId: this.$store.state.workflow.businessConfig.id,
        pageNo: 0,
        pageSize: 0,
        params: {},
        paymentTerms: "",
        priceTax: "",
        priceinfoId: "",
        rateType: "",
        rate: "",
        remark: "",
        saleDate: "",
        saleDept: "",
        saleDeptName: "",
        saleGroup: "",
        saleGroupName: "",
        saleId: "",
        saleName: "",
        saleQuotationCode: "",
        searchValue: "",
        settlementParty: "",
        settlementType: "",
        state: "",
        updateBy: "",
        updateTime: "",
        materialDetailEntities: [],
      },
      rules: {
        kingDocTypeId: [
          {
            required: true,
            message: "请选择单据类型",
            trigger: "change",
          },
        ],
        saleDate: [
          {
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
        customerName: [
          {
            required: true,
            message: "请选择客户",
            trigger: "blur",
          },
        ],
        customerName: [
          {
            required: true,
            message: "请选择客户",
            trigger: "blur",
          },
        ],
        materialName: [
          {
            required: true,
            message: "请选择物料名称",
            trigger: "blur",
          },
        ],
        purchaseUnitName: [
          {
            required: true,
            message: "请选择销售单位",
            trigger: "blur",
          },
        ],
      },
      documentTypeList: [],
    };
  },
  methods: {
    // 页签切换事件
    handleClick(tab, event) {},
    // 附件上传
    handleFileChange() {
      console.log("文件上传");
    },

    // 基础表单提交
    submit() {
      this.$refs["formRef"].validate((valid) => {
        if (!valid) return;
        // TODO 提交表单
        addQuotationList(this.formObject).then((res) => {
          if (res.code === 200) {
            this.$message({
              message: "新增成功！",
              type: "success",
            });
            this.$store.commit("workflow/SET_BUSINESSDRAWER", false);
          }
        });
      });
    },

    // 基础表单取消
    formRest(formRef) {
      this.$refs[formRef].resetFields();
    },
    // 删除行
    handleDataDelete(index, row, type) {
      this.$confirm("请确认是否要删除此行？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          if (type === "materialDetailEntities") {
            // 物料明细
            this.formObject.materialDetailEntities.splice(index, 1);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 物料明细 添加行
    addMaterialDetailEntities(index, row) {
      // 物料明细 obj
      let materialObj = this.getDetialObj();
      this.formObject.materialDetailEntities.push(materialObj);
    },

    //添加新行
    addNewRow(type) {
      if (type === "materialDetailEntities") {
        this.addMaterialDetailEntities(); //物料明细
      }
    },
    // 处理弹窗弹出
    handleOpen() {
      const nameMap = {
        customer: () => {
          this.dialogTitle = "选择客户";
          this.currentCom = Customer;
        },
        saleDept: () => {
          this.dialogTitle = "选择销售部门";
          this.currentCom = SaleDept;
        },
        saleId: () => {
          this.dialogTitle = "选择销售员";
          this.currentCom = SaleId;
        },
        saleGroup: () => {
          this.dialogTitle = "选择销售组";
          this.currentCom = BusinessGroup;
        },
        material: () => {
          this.dialogTitle = "选择物料";
          this.currentCom = QueryMaterialList;
        },
        unit: () => {
          this.dialogTitle = "选择单位";
          this.currentCom = PriceUnit;
        },
        priceUnit: () => {
          this.dialogTitle = "选择单位";
          this.currentCom = PriceUnit;
        },
        taxRate: () => {
          this.dialogTitle = "选择税率";
          this.currentCom = TaxRate;
        },
        currency: () => {
          this.dialogTitle = "选择币别";
          this.currentCom = Currency;
        },
      };
      nameMap[this.dialogType] ? nameMap[this.dialogType]() : "";
    },
    // 选择弹窗 item
    getSelectVal(val) {
      this.selectItem = val;
    },
    //点击选择dialog中的一条数据回显
    addDialog(type, index) {
      this.dialog = true;
      this.dialogType = type;
      this.dialogIndex = index;
      this.handleOpen();
    },

    // 创建组织
    selectOrg() {
      this.showOrg = true;
      let level = 1;
      listDept({ level }).then((res) => {
        if (res.code === 200) {
          this.orgData = res.data;
        }
        return;
      });
    },
    // 创建组织item
    selectOrgItem(val) {
      if (val.length === 1) {
        this.orgSelect = val;
        this.showOrg = false;
      }
    },
    //获取单据类型
    getDocTypeListApi() {
      getDocTypeList({ docCode: "SAL_QUOTATION" }).then((res) => {
        if (res.code === 200) {
          this.documentTypeList = res.rows;
        }
      });
    },
    //下拉类型选择
    handleCommand(val) {
      this.dialogType = val;
      this.dialog = true;
      this.handleOpen();
    },

    cancelSelect() {
      this.dialog = false;
      this.selectItem = [];
    },
    confirmSelect() {
      const nameMap = {
        customer: () => {
          if (this.selectItem.length !== 1) {
            this.$message.error("请选择一条数据！");
            return;
          }
          this.formObject.customerId = this.selectItem[0].id;
          this.formObject.customerName = this.selectItem[0].customerName;
          this.dialog = false;
        },

        saleDept: () => {
          if (this.selectItem.length !== 1) {
            this.$message.error("请选择一条数据！");
            return;
          }
          this.formObject.saleDept = this.selectItem[0].deptId;
          this.formObject.saleDeptName = this.selectItem[0].deptName;
          this.dialog = false;
        },
        saleId: () => {
          if (this.selectItem.length !== 1) {
            this.$message.error("请选择一条数据！");
            return;
          }
          this.formObject.saleId = this.selectItem[0].userId;
          this.formObject.saleName = this.selectItem[0].userName;
          this.dialog = false;
        },
        saleGroup: () => {
          if (this.selectItem.length !== 1) {
            this.$message.error("请选择一条数据！");
            return;
          }
          this.formObject.saleGroup = this.selectItem[0].id;
          this.formObject.saleGroupName = this.selectItem[0].businessGroupType;
          this.dialog = false;
        },
        material: () => {
          if (this.selectItem.length !== 1) {
            this.$message.error("请选择一条数据！");
            return;
          }
          this.selectItem.forEach((item) => {
            let materialObj = this.getDetialObj();
            Object.keys(item).forEach((itemKey) => {
              Object.keys(materialObj).forEach((materialKey) => {
                if (itemKey === materialKey) {
                  materialObj[materialKey] = item[itemKey];
                }
                if (itemKey === "id") {
                  materialObj["id"] = "";
                }
              });
            });
            this.$set(
              this.formObject.materialDetailEntities,
              this.dialogIndex,
              materialObj
            );
          });
          this.dialog = false;
        },
        unit: () => {
          if (this.selectItem.length !== 1) {
            this.$message.error("请选择一条记录！");
            return;
          }

          // 销售单位 purchaseUnit
          this.formObject.materialDetailEntities[
            this.dialogIndex
          ].purchaseUnit = this.selectItem[0].meteringUnitCode;
          this.formObject.materialDetailEntities[
            this.dialogIndex
          ].purchaseUnitName = this.selectItem[0].meteringUnitName;
          this.dialog = false;
        },
        priceUnit: () => {
          if (this.selectItem.length !== 1) {
            this.$message.error("请选择一条记录！");
            return;
          }
          // 计价单位
          this.formObject.materialDetailEntities[this.dialogIndex].pricingUnit =
            this.selectItem[0].meteringUnitCode;
          this.formObject.materialDetailEntities[
            this.dialogIndex
          ].pricingUnitName = this.selectItem[0].meteringUnitName;
          this.dialog = false;
        },
        taxRate: () => {
          if (this.selectItem.length !== 1) {
            this.$message.error("请选择一条记录！");
            return;
          }
          // 税率
          this.formObject.materialDetailEntities[this.dialogIndex].taxRate =
            this.selectItem[0].rate;
          this.caculateNum(
            this.formObject.materialDetailEntities[this.dialogIndex],
            this.dialogIndex
          );
          this.dialog = false;
        },
        currency: () => {
          if (this.selectItem.length !== 1) {
            this.$message.error("请选择一条记录！");
            return;
          }
          this.formObject.currency = this.selectItem[0].id;
          this.formObject.currencyName = this.selectItem[0].currencyName;
          this.formObject.rate = this.selectItem[0].rate;
          this.caculateNum(
            this.formObject.materialDetailEntities[this.dialogIndex],
            this.dialogIndex
          );
          this.dialog = false;
        },
      };
      nameMap[this.dialogType] ? nameMap[this.dialogType]() : "";
    },
    getDetialObj() {
      return {
        amountMoney: "",
        batchNum: "",
        businessPrice: "",
        businessTaxPrice: "",
        businessType: "",
        changeTime: "",
        changeType: "",
        createTime: "",
        deliveryAddress: "",
        deliveryDate: "",
        deliveryLocation: "",
        discountAmount: "",
        discountRate: "",
        executeStatus: "",
        id: "",
        instanceId: "",
        inventoryId: "",
        inventoryNum: 0,
        inventoryUnit: "",
        isGiveaway: true,

        limit: 0,
        lineNumber: "",
        material: {
          allowAsset: "",
          allowInventory: "",
          allowOutsource: "",
          allowProduce: "",
          allowPurchase: "",
          allowSale: "",
          barCode: "",
          brand: "",
          businessType: "",
          configurationProduction: "",
          costPriceRatio: "",
          createBy: "",
          createTime: "",
          dataState: "",
          defaultTaxRate: "",
          deptId: "",
          disableBy: "",
          examineBy: "",
          examineTime: "",
          grossWeight: "",
          heightStr: "",
          id: "",
          imgUrl: "",
          instanceId: "",
          inventoryType: "",
          isChange: "",

          kit: "",
          lengthStr: "",
          materialCode: "",
          materialDesc: "",
          materialGroup: "",
          materialInventoryEntity: {
            batchInfo: "",
            batchRule: "",
            checkCycle: "",
            convertDirection: "",
            costUnit: "",
            createBy: "",
            createTime: "",
            currency: "",
            day: "",
            economicOrderingBatch: "",
            id: "",
            inventoryUnit: "",
            isBatch: "",
            isCheck: "",
            isLock: "",
            isMaxInventory: "",
            isMinInventory: "",
            isOrderGoods: "",
            isSafeInventory: "",
            isTrueCheck: "",
            materialId: "",
            maxInventoyNum: "",
            minInventoryNum: "",
            orderGoodsNum: "",
            pageNo: 0,
            pageSize: 0,
            params: {},
            qualityManage: "",
            qualityNum: "",
            qualityUnit: "",
            referenceCost: "",
            remark: "",
            safeInventoryNum: "",
            searchValue: "",
            serviceLife: "",
            standardNumber: "",
            supportUnit: "",
            updateBy: "",
            updateTime: "",
            warePosition: "",
            warehouseCode: "",
          },
          materialName: "",
          materialPlanAttributeEntity: {
            createBy: "",
            createTime: "",
            fAllowPartDelay: "",
            fBaseVarLeadTimeLotSize: "",
            fBaseVarLeadTimeLotSizeUnit: "",
            fCanDelayDays: 0,
            fCanLeadDays: 0,
            fCheckLeadTime: 0,
            fCheckLeadTimeType: "",
            fDelayExtendDay: 0,
            fFixLeadTime: 0,
            fFixLeadTimeType: "",
            fIncreaseQty: 0,
            fIncreaseQtyUnit: "",
            fIsMrpComBill: "",
            fIsMrpComReq: "",
            fLeadExtendDay: 0,
            fMaxPoqty: 0,
            fMfgPolicyId: "",
            fMinPoqty: 0,
            fMinPoqtyUnit: "",
            fOrderIntervalTime: 0,
            fOrderIntervalTimeType: "",
            fOrderPolicy: "",
            fPlanBatchSplitQty: "",
            fPlanBatchSplitQtyUnit: "",
            fPlanGroupId: "",
            fPlanIdent: "",
            fPlanIntervalsDays: 0,
            fPlanOffsetTime: 0,
            fPlanOffsetTimeType: "",
            fPlanSafeStockQty: 0,
            fPlanSafeStockQtyUnit: "",
            fPlanTimeZone: 0,
            fPlanWorkshop: "",
            fPlanerId: "",
            fPlanningStrategy: "",
            fProScheTrackId: "",
            fProductLine: "",
            fRequestTimeZone: 0,
            fSupplySourceId: "",
            fVarLeadTime: 0,
            fVarLeadTimeLotSize: "",
            fVarLeadTimeLotSizeUnit: "",
            fVarLeadTimeType: "",
            fWriteOffQty: "",
            fWriteOffQtyUnit: "",
            id: "",
            materialId: "",
            maxPoqtyUnit: "",
            pageNo: 0,
            pageSize: 0,
            params: {},
            remark: "",
            searchValue: "",
            updateBy: "",
            updateTime: "",
          },
          materialProcureEntity: {
            agentProcure: "",
            barCodeRule: "",
            createBy: "",
            createTime: "",
            dayProduction: 0,
            dayProductionUnit: "",
            defaultSupplier: "",
            defunctProductionLine: "",
            expenseItem: "",
            id: "",
            isControl: "",
            isDayProduction: "",
            isMaterialReturn: "",
            isQuota: "",
            isReq: "",
            materialId: "",
            minPackNum: "",
            minSpiltNum: 0,
            outsourcePricingUnit: "",
            outsourceType: "",
            outsourceUnit: "",
            pageNo: 0,
            pageSize: 0,
            params: {},
            procureGroup: "",
            procureId: "",
            procurePricingUnit: "",
            procureType: "",
            procureUnit: "",
            quotaMode: "",
            remark: "",
            repeatPutNum: "",
            searchValue: "",
            takeOverDelay: 0,
            takeOverDown: "",
            takeOverLead: 0,
            takeOverUp: "",
            updateBy: "",
            updateTime: "",
          },
          materialProductEntity: {
            createBy: "",
            createTime: "",
            deptId: "",
            fBackFlushType: "",
            fConsumVolatility: "",
            fDefaultLineId: "",
            fDefaultRouting: "",
            fFinishReceiptOverRate: "",
            fFinishReceiptShortRate: "",
            fIsCompleteSet: "",
            fIsEnableSchedule: "",
            fIsKitting: "",
            fIsMainPrd: "",
            fIsMinissueQty: "",
            fIsProductLine: "",
            fIsSNCarryToParent: "",
            fIssueType: "",
            fMdlId: "",
            fMdlMaterialId: "",
            fMinissueQty: 0,
            fMinissueUnitId: "",
            fOrgTrustBillType: "",
            fOverControlMode: "",
            fPerUnitStandHour: "",
            fPickBinId: "",
            fPickStockId: "",
            fProduceBillType: "",
            fProduceUnitId: "",
            fStandHourUnitId: "",
            fStdLaborPrePareTime: "",
            fStdLaborProcessTime: "",
            fStdMachinePrepareTime: "",
            fStdMachineProcessTime: "",
            fWorkShopId: "",
            fbkfltime: "",
            fbomunitid: "",
            ffixloss: "",
            fisecn: "",
            flosspercent: "",
            id: "",
            materialId: "",
            pageNo: 0,
            pageSize: 0,
            params: {},
            remark: "",
            searchValue: "",
            updateBy: "",
            updateTime: "",
          },
          materialProperty: "",
          materialQualityEntity: {
            createBy: "",
            createTime: "",
            fCheckDelivery: "",
            fCheckEntrusted: "",
            fCheckIncoming: "",
            fCheckOther: "",
            fCheckProduct: "",
            fCheckReturn: "",
            fCheckStock: "",
            fCheckSubFtnMtrl: "",
            fEWLeadDay: "",
            fEnableCyclistQCSTK: "",
            fEnableCyclistQcstkew: "",
            fFirstQCControlType: "",
            fIncQcSchemeId: "",
            fIncSampSchemeId: "",
            fInspectGroupId: "",
            fInspectorId: "",
            fIsFirstInspect: "",
            fStockCycle: "",
            id: "",
            materialId: "",
            pageNo: 0,
            pageSize: 0,
            params: {},
            remark: "",
            searchValue: "",
            updateBy: "",
            updateTime: "",
          },
          materialSaleEntity: {
            allowReleaseOrder: "",
            allowReturns: "",
            atpCheck: "",
            controlSurpassUnit: "",
            createBy: "",
            createTime: "",
            dropOutCount: "",
            fisReturnPart: "",
            fisaftersale: "",
            fisproductfiles: "",
            fiswarranted: "",
            fwarranty: "",
            fwarrantyunitid: "",
            id: "",
            isFavourableTax: "",
            materialId: "",
            pageNo: 0,
            pageSize: 0,
            params: {},
            remark: "",
            saleDownPrice: "",
            saleGroup: "",
            saleOutbound: "",
            salePricingUnit: "",
            saleUnit: "",
            searchValue: "",
            startOrderNum: 0,
            surpassDown: "",
            surpassUp: "",
            taxType: "",
            taxTypeCode: "",
            updateBy: "",
            updateTime: "",
          },
          mnemonicCode: "",
          model: "",
          modelId: "",
          netWeight: "",
          oldMaterialCode: "",
          pageNo: 0,
          pageSize: 0,
          params: {},
          reasonForDisable: "",
          remark: "",
          searchValue: "",
          sizeUnit: "",
          state: "",
          subItems: "",
          taxType: "",
          typeName: "",
          unit: "",
          updateBy: "",
          updateTime: "",
          volume: "",
          weightUnit: "",
          wideStr: "",
        },
        materialChangeEntity: {},
        materialCode: "",
        materialName: "",
        model: "",
        materialId: "",
        modelId: "",
        netAmount: "",
        noTaxMoney: "",
        number: "",
        orderDelivery: {
          batchNum: "",
          bomVer: "",
          changeTime: "",
          controlDeliveryNum: true,
          controlDeliveryTime: true,
          createTime: "",
          deliveryDelayDay: "",
          deliveryDown: "",
          deliveryEarlyTime: "",
          deliveryLatestTime: "",
          deliveryLeadDay: "",
          deliveryUp: "",
          id: "",

          materialId: "",
          materialName: "",
          orderDeliveryDetails: [
            {
              address: "",
              changeTime: "",
              confirmComment: "",
              confirmNum: "",
              confirmTime: "",
              createTime: "",
              deliveredNum: "",
              deliveryTime: "",
              id: "",

              location: "",
              num: "",
              orderDeliveryId: "",
              orderId: "",
              planUnit: "",
              surplusNum: "",
              userId: "",
            },
          ],
          orderId: "",
          receiveDept: "",
          receiveOrg: "",
          requireDept: "",
          requireOrg: "",
          supplierBatch: "",
          supportAttr: "",
          userId: "",
        },
        orderFinanceDetail: {
          changeTime: "",
          createTime: "",
          discountAmount: "",
          discountRate: "",
          entryPriceInfo: "",
          id: "",

          materialCode: "",
          materialId: "",
          materialName: "",
          netPrice: "",
          orderId: "",
          priceCeiling: "",
          priceCoefficient: "",
          priceFloor: "",
          pricingNum: "",
          pricingUnit: "",
          settlementDept: "",
          systemPricing: "",
          taxRate: "",
          unitPriceDiscount: "",
          userId: "",
        },
        orderOther: {
          businessClose: "",
          businessFreeze: "",
          businessProcess: "",
          businessStop: "",
          changeTime: "",
          contractsCode: "",
          createTime: "",
          freezeName: "",
          freezeTime: "",
          id: "",
          inventoryReturnNum: "",
          isPlanConfirm: "",
          isQuotaGeneration: "",

          materialCode: "",
          materialId: "",
          materialName: "",
          materialReceivedReturnNum: "",
          orderId: "",
          planTrackingCode: "",
          requireDocCode: "",
          requireDocLineCode: "",
          requireFrom: "",
          requireTrackingCode: "",
          sourceDocCode: "",
          sourceDocType: "",
          stopName: "",
          stopTime: "",
          surplusInboundNum: "",
          surplusMaterialReceivedNum: "",
          totalInboundNum: "",
          totalMaterialReceivedNum: "",
          totalMaterialReturnNum: "",
          updateFlag: "",
          userId: "",
        },
        originalContainsTaxPrice: "",
        originalNumber: "",
        page: 0,
        parentMaterial: "",
        price: "",
        pricingNum: "",
        pricingUnit: "",
        pricingUnitName: "",
        purchaseUnit: "",
        purchaseUnitName: "",
        ramarks: "",
        receivedFirstTicketsNum: "",
        receivingDept: "",
        relationId: "",
        requireDept: "",
        saleOrderDelivery: {
          createBy: "",
          createTime: "",
          deliveryDown: "",
          deliveryType: "",
          deliveryUnit: "",
          deliveryUp: "",
          id: "",
          inventoryDept: "",

          materialCode: "",
          materialName: "",
          orderId: "",
          pageNo: 0,
          pageSize: 0,
          params: {},
          remark: "",
          saleOrderDeliveryDetailEntities: [
            {
              createBy: "",
              createTime: "",
              deliveryAddress: "",
              deliveryAddressDetail: "",
              deliveryDate: "",
              deliveryId: "",
              id: "",
              inAdvance: "",

              pageNo: 0,
              pageSize: 0,
              params: {},
              planDeliveryDate: "",
              remark: "",
              saleNum: "",
              saleUnit: "",
              searchValue: "",
              updateBy: "",
              updateTime: "",
            },
          ],
          searchValue: "",
          updateBy: "",
          updateTime: "",
        },
        settlementDept: "",
        sourceDocCode: "",
        sourceDocType: "",
        sourceMaterialDetailId: "",
        sourceRelationId: "",
        state: "",
        supplierMaterialCode: "",
        supplierMaterialName: "",
        taxAmount: "",
        taxMoney: "",
        taxPrice: "",
        taxRate: "",
        token: "",
        totalAcceptanceAmount: "",
        totalAcceptanceRate: "",
        totalTaxPrice: "",
        type: 0,
        warehouseCode: "",
        warehouseId: "",
        warehouseRegionId: "",
      };
    },
    // 计算值
    caculateNum(row, index) {
      // 数量，税率，价税合计，汇率
      console.log("触发", row);
      if (row == undefined) {
        return;
      }
      if (
        row.number &&
        row.taxRate &&
        row.totalTaxPrice &&
        this.formObject.rate
      ) {
        let totalTaxAmount = row.totalTaxPrice;
        let number = row.number;
        let taxRate = row.taxRate;
        let rate = this.formObject.rate;
        getCompute({ number, taxRate, totalTaxAmount, rate }).then((res) => {
          this.$set(
            this.formObject.materialDetailEntities[index],
            "price",
            res.data.price
          );
          this.$set(
            this.formObject.materialDetailEntities[index],
            "amountMoney",
            res.data.amount
          );

          this.$set(
            this.formObject.materialDetailEntities[index],
            "taxAmount",
            res.data.taxAmount
          );

          this.$set(
            this.formObject.materialDetailEntities[index],
            "taxPrice",
            res.data.taxUnitPrice
          );
        });
      }
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
          return;
        }
        if (
          column.property === "number" ||
          column.property === "pricingNum" ||
          column.property === "amountMoney" ||
          column.property === "taxAmount" ||
          column.property === "totalTaxPrice"
        ) {
          const values = data.map((item) => Number(item[column.property]));
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += "";
          } else {
            sums[index] = "N/A";
          }
        } else {
          return;
        }
      });

      return sums;
    },
  },
  created() {
    this.getDocTypeListApi();
  },
};
</script>
<style lang="scss" scoped>
// .add {
//   padding: 15px;
// }
.panel-title {
  font-size: 18px;
  color: #37474f;
  font-weight: 500;
  text-shadow: rgba(0, 0, 0, 0.15) 0 0 1px;
}

::v-deep .el-form-item__content {
  margin-left: 0;
}

.main-responsible {
  font-size: 14px;
  font-weight: 550;
  color: #263238;
  position: relative;
  text-indent: 15px;
}
::v-deep .el-table td.el-table__cell div {
  overflow: visible;
}

::v-deep .el-table td.el-table__cell {
  padding-bottom: 20px;
}
</style>
